#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from kill import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import subprocess
from collections import Counter


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowIcon(QIcon("logo.ico"))
        self.setupUi(self)
        self.status = self.statusBar()
        self.close_btn.setEnabled(False)
        self.query_btn.clicked.connect(self.click_query)
        self.close_btn.clicked.connect(self.click_close_pid)

    def click_query(self):
        port = self.portLineEdit.text()
        if port == '':
            QMessageBox.about(self, '提示', '请输入查询端口')
            return
        self.status.showMessage('正在查询' + str(port), 0)
        port_pid = find_pid(self.portLineEdit.text())
        self.portResultPid.setText(port_pid)
        self.status.showMessage('查询结果:' + str(port_pid), 0)
        if port_pid is not None:
            self.close_btn.setEnabled(True)
        else:
            QMessageBox.about(self, '提示', '没有查询到进程')
            self.close_btn.setEnabled(False)

    def click_close_pid(self):
        pid = self.portResultPid.text()
        if pid == '' or pid == '无':
            QMessageBox.about(self, '提示', '请查询关闭的pid')
            return
        find_kill = 'taskkill -f -pid %s' % pid
        try:
            proc = subprocess.Popen(find_kill, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE,
                                    close_fds=False, text=True)
            # 既然没有命令行窗口，那就关闭输入
            proc.wait()
            result = proc.stdout.read()
            if result == '':
                result = '关闭错误'
            else:
                self.close_btn.setEnabled(False)
            QMessageBox.about(self, '结果', str(result))
        except Exception as e:
            QMessageBox.about(self, '结果', '错误')

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
            self.click_query()


def find_pid(port):
    """
     查询指定的端口 pid
    :param port:  端口号
    :return:  pid
    """
    find_str = 'netstat -aon | findstr :%s' % str(port)
    proc = subprocess.Popen(find_str, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                            close_fds=False)
    proc.stdin.close()
    proc.wait()
    result = proc.stdout.read()
    proc.stdout.close()
    data_array = result.decode().split('\n')
    list_pid = []
    for item in data_array:
        if len(item.split()) == 5:
            a = item.split()[4]
            if a != '0':
                list_pid.append(a)
    result_pid = Counter(list_pid).most_common(1)
    if len(result_pid) == 1:
        pid, pid_count = result_pid[0]
        return pid
    return None
